package com.bsi.com.bsi.config;

import com.bsi.com.bsi.dao.UserDao;
import com.bsi.com.bsi.dto.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCrypt;

import java.util.List;

/**
 * @ClassName OvitUserDetailsService
 * @Author LiuSong
 * @Date 2020/8/12 15:15
 * @Version 1.0
 * @Description 自定义userDetailService来根据用户名查询用户
 */
public class OvitUserDetailsService implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询数据库 此处用静态数据
//        if (!"zhangsan".equals(username)) {
//            throw new UsernameNotFoundException(username + " not found");
//        }
//        UserDetails userDetails = User.withUsername(username).password(BCrypt.hashpw("1234",BCrypt.gensalt())).authorities("/r/r1").build();
        UserDto user = userDao.findUserByName(username);
        if (user == null) {
            throw new UsernameNotFoundException(username + " not found");
        }
        List<String> permissionByUserId = userDao.findPermissionByUserId(user.getId());
        String[] strings = permissionByUserId.toArray(new String[permissionByUserId.size()]);
        UserDetails userDetails = User.withUsername(user.getUsername()).password(user.getPassword()).authorities(strings).build();
        return userDetails;
    }
}
